import {createRouter, createWebHashHistory } from 'vue-router'
import {defineAsyncComponent} from 'vue'

const routes = [
    {path: '/', component: () => import('@/components/Home.vue'),
    meta: {
        prerender: true,
        title: '预渲染的路由页面',
        keywords: 'keywords: 关键词1, 关键词2',
        description: '预渲染描述description'
    }},
    {path: '/hello', component: defineAsyncComponent(() => import('@/components/HelloWorld.vue'))},
    {path: '/about', component: () => import('@/components/About.vue')},
    {
        path: '/prerender',
        component: () => import('@/components/Prerender.vue'),
        meta: {
            prerender: true,
            title: '预渲染的路由页面',
            keywords: 'keywords: 关键词1, 关键词2',
            description: '预渲染描述description'
        }
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})
router.beforeEach((to) => {
    const {prerender,title,keywords,description} = to.meta
    if(prerender) {
        // 预渲染添加meta seo优化信息 TDK ，也可以用vue-meta-info代替
        console.log('document',document)
        if(description) {
            document.title = title
        }
        const metas = document.getElementsByTagName('meta')
        console.log('metas',metas);
        for(let i=0;i<metas.length; i++) {
            const meta = metas[i]
            if(meta.name === 'keywords' && keywords) {
                meta.content = keywords
            }
            if(meta.name === 'description' && description) {
                meta.content = description
            }
        }
    }
    
})

export default router